// pages/customer/submit.js
import Validate from "../../utils/validate";

const app = getApp();
const network = require("../../utils/network.js");
const util = require("../../utils/util.js");
const {formatDate} = require("../../utils/util");
import Toast from '@vant/weapp/toast/toast';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        customer: {
            id: null,
            name: null,// 名称
            industry_id: null,// 行业id
            address: null,// 地址
            funnels: [],// 销售漏斗
            selection_reasons: [],// 选择原因
            budget: null,// 预算
            person_in_charge_id: null,// 负责人id
            group: null,// 所属集团id
            company_launch_background: null,// 客户投放背景
            company_programme: null,//客户方案
            contactsList: [{
                name: null,// 名称
                dept: null,// 部门
                post: null,// 职务
                phone: null,// 手机号
                level: null,//等级
                birthday: null,// 生日
                hobbies: null,// 个人喜好
                commemoration_day: null,// 家庭成员及重要纪念日
                remark: null// 备注
            }],
            putStorageList: [{
                company_head: null,//公司抬头
                login_account: null,//登录账号
                password: null,
                link_user: null,
                phone: null,
                email: null,
                website: null,// 网站
            }],
            follows: [{
                follow_time: null,
                opposite_person: null,// 联系人
                phone: null,
                action_list: [],
                resource_list: [],
                url_list: [],
                reasons_for_recommendation: null,// 拜访目的
                achievements: null,// 达成成果
            }],
            industry_name: null,// 显示文本
            group_name: null,// 显示文本
            person_in_charge_name: null,// 显示文本
        },
        industryPopShow: false,
        groupPopShow: false,
        userSelectShow: false,
        calendarShow: false,
        levelShow: false,
        companyShow: false,
        birthdayShow: false,
        industry_arr: [],// 行业待选项
        salesFunnelArr: [],// 销售漏斗待选项
        groupArr: [],//所属集团待选项
        userArr: [],// 客户负责人待选项
        selectReasonArr: [],// 选择原因待选项
        actionArr: [],// 推进动作待选项
        resourceArr: [], // 推荐资源待选项
        companyArr: [], // 公司待选项
        linkUserArr: [],// 待选项
        levelArr: ['总负责人', '直接负责人', '办事员'],
        index: -1,// 联系人点击弹框时的下标
        tmpIndex: -1,// 入库信息点击弹框时的下标
        followIndex: -1,// 跟进记录点击弹框时的下标
        date: null,
        minDate: new Date(new Date().getFullYear() - 60, 0, 1).getTime(),
        maxDate: new Date().getTime(),
        calendarMaxDate: new Date().getTime(),
        active: 0,
        linkUserShow: false,
        validate: {},
        validateContacts: {},
        validatePutStorage: {},
        validateFollows: {},
        wf_data_id: null,
        create: true,
        user_id: wx.getStorageSync('user_id'),
    },
    // 验证函数
    initValidate() {
        const rules = {
            name: {
                required: true
            },
            industry_id: {
                required: true
            },
            address: {
                required: true,
            },
            person_in_charge_id: {
                required: true
            },
            group: {
                required: true
            }
        }
        const messages = {
            name: {
                required: '请输入项目名称'
            },
            industry_id: {
                required: '请选择行业'
            },
            address: {
                required: '请输入客户地址',
            },
            person_in_charge_id: {
                required: '请选择客户负责人'
            },
            group: {
                required: '请选择集团'
            },
        }
        this.data.validate = new Validate(rules, messages)
    },
    // 验证函数
    initValidateContacts() {
        const rules = {
            name: {
                required: true
            },
            phone: {
                required: true,
                tel: true
            }
        }
        const messages = {
            name: {
                required: '请输入联系人名称'
            },
            phone: {
                required: '请输入手机号',
                tel: '请输入正确的手机号'
            }
        }
        this.data.validateContacts = new Validate(rules, messages)
    },
    // 验证函数
    initValidatePutStorage() {
        const rules = {
            website: {
                required: true,
                url: true
            },
            company_head: {
                required: true
            },
            login_account: {
                required: true
            },
            password: {
                required: true
            }
        }
        const messages = {
            website: {
                required: '请输入网址',
                url: '请输入正确的网址'
            },
            company_head: {
                required: '请选择公司抬头'
            },
            login_account: {
                required: '请输入登录账号'
            },
            password: {
                required: '请输入登录密码'
            }
        }
        this.data.validatePutStorage = new Validate(rules, messages)
    },
    // 验证函数
    initValidateFollows() {
        const rules = {
            follow_time: {
                required: true,
            },
            opposite_person: {
                required: true
            },
            reasons_for_recommendation: {
                required: true
            },
            achievements: {
                required: true
            }
        }
        const messages = {
            follow_time: {
                required: '请选择沟通日期'
            },
            opposite_person: {
                required: '请选择对接人'
            },
            reasons_for_recommendation: {
                required: '请输入拜访目的'
            },
            achievements: {
                required: '请输入达成成果'
            }
        }
        this.data.validateFollows = new Validate(rules, messages)
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        util.showLoading('加载中')
        if (options.wf_data_id) {
            this.setData({
                wf_data_id: options.wf_data_id,
                create: false
            })
        }
        const that = this
        this.initValidate()
        this.initValidateContacts()
        this.initValidatePutStorage()
        this.initValidateFollows()
        Promise.all([
            this.getDictList('khxg-hy', 'industry_arr', '行业数据初始化失败'),
            this.getDictList('khxg-xzyy', 'selectReasonArr', '选择原因数据初始化失败'),
            this.getDictList('khxg-xsld', 'salesFunnelArr', '销售漏斗数据初始化失败'),
            this.getDictList('khxg-tjzy', 'resourceArr', '推荐资源数据初始化失败'),
            this.getDictList('khxg-tjdz', 'actionArr', '推进动作数据初始化失败'),
            this.getDictList('khxg-ssjt', 'groupArr', '所属集团数据初始化失败'),
            this.getCompanyArr(),
            this.getUserArr()
        ]).then(() => {
            util.hideLoading()
            if (options.id) {
                network.reqPromise('GET', {
                    uri: app.api.customerDetail,
                    params: {id: options.id},
                }).then(res => {
                    res.data.follows.forEach(item => {
                        item.url_list = item.url_list.map(img => {
                            return {
                                url: img,
                                type: 'image',
                                isImage: true
                            }
                        })
                        item.resource_list = item.resource_list.map(i => {
                            return i.toString()
                        })
                        item.action_list = item.action_list.map(i => {
                            return i.toString()
                        })
                    })
                    res.data.funnels = res.data.funnels.map(i => {
                        return i.toString()
                    })
                    res.data.selection_reasons = res.data.selection_reasons.map(i => {
                        return i.toString()
                    })
                    that.setData({
                        customer: res.data
                    })
                    this.watch()
                }).catch(() => {

                })
            }
        }).catch(() => {
            util.hideLoading()
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.selectComponent('.flow-btn-group').callbackBeforeConfirm = this.validForm;
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //初始化字典数据
    getDictList(code, data, failMsg) {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.getDictData,
                params: {code: code}
            }).then(res => {
                that.setData({
                    [data]: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: failMsg,
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 初始化子公司数据
    getCompanyArr() {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.companyList
            }).then(res => {
                that.setData({
                    companyArr: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: '初始化公司数据失败',
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 初始化人员信息
    getUserArr() {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.allUserList
            }).then(res => {
                that.setData({
                    userArr: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: '初始化用户数据失败',
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 显示收缩内容
    onChange(event) {
        this.setData({
            active: event.detail.index,
        });
    },
    // 输入框输change
    onInputChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail
        })
        this.watch()
    },
    // 显示弹出层
    showPopup(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        let key = e.target.dataset.show;
        this.setData({
            [key]: true
        })
    },
    // 确认选择行业
    onConfirmIndustry(e) {
        this.setData({
            'customer.industry_id': e.detail.value.id,
            'customer.industry_name': e.detail.value.name,
            industryPopShow: false
        });
    },
    // 确认选择集团
    onConfirmGroup(e) {
        this.setData({
            'customer.group': e.detail.value.id,
            'customer.group_name': e.detail.value.name,
            groupPopShow: false
        });
    },
    // 确认选择客户负责人
    onConfirmUser(e) {
        this.setData({
            'customer.person_in_charge_id': e.detail.value.id,
            'customer.person_in_charge_name': e.detail.value.name,
            userSelectShow: false
        });
    },
    // 取消选择
    onCancelPop(e) {
        let key = e.target.dataset.show;
        this.setData({
            [key]: false,
            index: -1,
            tmpIndex: -1,
            followIndex: -1
        });
    },
    // 多选框选择事件
    onCheckBoxChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail,
        });
    },
    showCalendar(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        this.setData({
            calendarShow: true,
            followIndex: e.target.dataset.index
        });
    },
    onCalendarConfirm(e) {
        let key = 'customer.follows[' + this.data.followIndex + '].follow_time'
        this.setData({
            [key]: formatDate(e.detail),
            calendarShow: false,
            followIndex: -1
        });
    },
    onCalendarClose() {
        this.setData({
            followIndex: -1,
            calendarShow: false
        });
    },
    addLinkUser() {
        this.data.customer.contactsList.push({
            name: null,// 名称
            dept: null,// 部门
            post: null,// 职务
            phone: null,// 手机号
            level: null,//等级
            birthday: null,// 生日
            hobbies: null,// 个人喜好
            commemoration_day: null,// 家庭成员及重要纪念日
            remark: null// 备注
        });
        this.setData({
            'customer.contactsList': this.data.customer.contactsList
        })
        this.watch()
    },
    removeLinkUser(e) {
        this.data.customer.contactsList.splice(e.target.dataset.index, 1);
        this.setData({
            'customer.contactsList': this.data.customer.contactsList
        })
        this.watch()
    },
    addPutStorage() {
        this.data.customer.putStorageList.push({
            company_head: null,//公司抬头
            login_account: null,//登录账号
            password: null,
            link_user: null,
            phone: null,
            email: null,
            website: null,// 网站
        });
        this.setData({
            'customer.putStorageList': this.data.customer.putStorageList
        })
    },
    removePutStorage(e) {
        this.data.customer.putStorageList.splice(e.target.dataset.index, 1);
        this.setData({
            'customer.putStorageList': this.data.customer.putStorageList
        })
    },
    addFollow() {
        this.data.customer.follows.push({
            follow_time: null,
            opposite_person: null,// 联系人
            phone: null,
            action_list: [],
            resource_list: [],
            url_list: [],
            reasons_for_recommendation: null,// 拜访目的
            achievements: null,// 达成成果
        });
        this.setData({
            'customer.follows': this.data.customer.follows
        })
    },
    removeFollow(e) {
        this.data.customer.follows.splice(e.target.dataset.index, 1);
        this.setData({
            'customer.follows': this.data.customer.follows
        })
    },
    removeImg(e) {
        let key = 'customer.follows[' + e.target.dataset.index + '].url_list'
        this.data.customer.follows[e.target.dataset.index].url_list.splice(e.detail.index, 1);
        this.setData({
            [key]: this.data.customer.follows[e.target.dataset.index].url_list
        })
    },
    showLevelPop(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        let key = e.target.dataset.show;
        this.setData({
            index: e.target.dataset.index,
            [key]: true
        })
    },
    onConfirmLevel(e) {
        let key = 'customer.contactsList[' + this.data.index + '].level'
        this.setData({
            index: -1,
            [key]: e.detail.value,
            levelShow: false
        })
    },
    showBirthday(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        let default_time;
        if (!e.target.dataset.default) {
            default_time = new Date().getTime()
        } else {
            default_time = new Date(e.target.dataset.default).getTime();
        }
        this.setData({
            birthdayShow: true,
            index: e.target.dataset.index,
            date: default_time
        });
    },
    onBirthdayConfirm(e) {
        let key = 'customer.contactsList[' + this.data.index + '].birthday'
        this.setData({
            [key]: formatDate(new Date(e.detail)),
            birthdayShow: false,
            index: -1
        });
    },
    showCompanyPop(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        this.setData({
            tmpIndex: e.target.dataset.index,
            companyShow: true
        })
    },
    onConfirmCompany(e) {
        let key = 'customer.putStorageList[' + this.data.tmpIndex + '].company_head'
        this.setData({
            [key]: e.detail.value.head,
            companyShow: false,
            index: -1
        });
    },
    showLinkUserPop(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        if (!this.data.linkUserArr || (this.data.linkUserArr && this.data.linkUserArr.length === 0)) {
            Toast.fail({
                message: '请先添加联系人信息',
                context: this,
                selector: '#custom-selector'
            })
            this.setData({
                active: 1
            })
            return
        }
        this.setData({
            linkUserShow: true,
            followIndex: e.target.dataset.index
        })
    },
    onConfirmLinkUser(e) {
        let key = 'customer.follows[' + this.data.followIndex + '].opposite_person'
        this.setData({
            linkUserShow: false,
            [key]: e.detail.value,
            followIndex: -1
        })
    },
    uploadFile(e) {
        util.showLoading("上传中")
        const that = this
        network.uploadFile(e.detail.file).then(res => {
            let key = 'customer.follows[' + e.target.dataset.index + '].url_list'
            that.data.customer.follows[e.target.dataset.index].url_list.push({
                url: res.data,
                type: 'image',
                isImage: true
            })
            that.setData({
                [key]: that.data.customer.follows[e.target.dataset.index].url_list
            })
            util.hideLoading()
        }).catch((err) => {
            console.log(err)
            Toast.fail({
                message: '上传失败',
                context: this,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    watch() {
        let arr = []
        this.data.customer.contactsList.forEach(item => {
            if (item.name) {
                arr.push(item.name)
            }
        })
        this.setData({
            linkUserArr: arr
        })
    },
    validForm() {
        if (!this.data.validate.checkForm(this.data.customer)) {
            this.setData({
                active: 0
            })
            Toast.fail({
                message: this.data.validate.errorList[0].msg,
                context: this,
                selector: '#custom-selector'
            })
            return false
        } else {
            // 检查漏斗信息
            if (this.data.customer.funnels.length) {
                // 检查联系人信息
                for (let i = 0; i < this.data.customer.contactsList.length; i++) {
                    const item = this.data.customer.contactsList[i]
                    if (!this.data.validateContacts.checkForm(item)) {
                        this.setData({
                            active: 1
                        })
                        Toast.fail({
                            message: this.data.validateContacts.errorList[0].msg,
                            context: this,
                            selector: '#custom-selector'
                        })
                        return false
                    }
                }
                // 检查跟进记录
                for (let i = 0; i < this.data.customer.follows.length; i++) {
                    const item = this.data.customer.follows[i]
                    if (!this.data.validateFollows.checkForm(item)) {
                        this.setData({
                            active: 3
                        })
                        Toast.fail({
                            message: this.data.validateFollows.errorList[0].msg,
                            context: this,
                            selector: '#custom-selector'
                        })
                        return false
                    } else {
                        if (!item.url_list.length) {
                            Toast.fail({
                                message: '请上传图片',
                                context: this,
                                selector: '#custom-selector'
                            })
                            return false
                        }
                    }
                }
                // 检查入库信息
                if (this.data.customer.putStorageList && this.data.customer.putStorageList.length) {
                    for (let i = 0; i < this.data.customer.putStorageList.length; i++) {
                        const item = this.data.customer.putStorageList[i]
                        if (!this.data.validatePutStorage.checkForm(item)) {
                            this.setData({
                                active: 2
                            })
                            Toast.fail({
                                message: this.data.validatePutStorage.errorList[0].msg,
                                context: this,
                                selector: '#custom-selector'
                            })
                            return false
                        }
                    }
                    return true
                } else {
                    return true
                }
            } else {
                Toast.fail({
                    message: '请选择漏斗信息',
                    context: this,
                    selector: '#custom-selector'
                })
                return false
            }
        }
    },
    save() {
        const that = this
        let req = this.data.customer;
        req.follows.forEach(item => {
            item.url_list = item.url_list.map(img => {
                return img.url
            })
        })
        util.showLoading('保存中')
        network.reqPromise('POST', {
            uri: app.api.saveCustomer,
            params: {
                data: that.data.customer,
                wfData_id: this.data.wf_data_id
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    submit() {
        const that = this
        let req = this.data.customer;
        req.follows.forEach(item => {
            item.url_list = item.url_list.map(img => {
                return img.url
            })
        })
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.submitCustomer,
            params: {
                data: that.data.customer,
                wfData_id: this.data.wf_data_id
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    pass(opinion) {
        const that = this
        let req = this.data.customer;
        req.follows.forEach(item => {
            item.url_list = item.url_list.map(img => {
                return img.url
            })
        })
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.customerCheck,
            params: {
                data: that.data.customer,
                opinion: opinion.detail,
                isCover: true,
                isReturn: false
            },
        }).then(res => {
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
            util.hideLoading()
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    returnBack(opinion) {
        const that = this
        let req = this.data.customer;
        req.follows.forEach(item => {
            item.url_list = item.url_list.map(img => {
                return img.url
            })
        })
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.customerCheck,
            params: {
                data: that.data.customer,
                opinion: opinion.detail,
                isCover: true,
                isReturn: true
            },
        }).then(res => {
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
            util.hideLoading()
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    del() {
        const that = this
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.customerDel,
            params: {
                flow_id: that.data.customer.id,
                wfData_id: this.data.wf_data_id
            },
        }).then(res => {
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
            util.hideLoading()
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    actDel() {
        const that = this
        let req = this.data.customer;
        req.follows.forEach(item => {
            item.url_list = item.url_list.map(img => {
                return img.url
            })
        })
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.customerActualDelete,
            params: {
                flow_id: that.data.customer.id,
                wfData_id: this.data.wf_data_id
            },
        }).then(res => {
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
            util.hideLoading()
        }).catch(() => {
            Toast.fail({
                message: '保存失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    back() {
        wx.navigateBack({
                delta: 1
            }
        )
    },
})
